package com.hps.shoping.order.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hps.shoping.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author heps
 * @date 2019/9/1 10:30
 */
@Component
@Slf4j
public class MessageConsumer {

    DefaultMQPushConsumer consumer;

    private final MessageProducer messageProducer;

    private final OrderService orderService;

    public MessageConsumer(MessageProducer messageProducer, OrderService orderService) {
        this.messageProducer = messageProducer;
        this.orderService = orderService;
        consumer = new DefaultMQPushConsumer("stock_group");
        consumer.setNamesrvAddr("192.168.117.139:9876");
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        try {
            consumer.subscribe("stockTopic", "*");
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                    for (MessageExt msg : msgs) {
                        String body = new String(msg.getBody(), Charset.defaultCharset());
                        JSONObject order = JSON.parseObject(body);
                        log.info("update order status {}", order.toJSONString());
                        String orderId = order.getString("orderId");
                        Byte status = order.getByte("status");
                        if (StringUtils.isNotEmpty(orderId) && status != null) {
                            try {
                                boolean result = orderService.updateStatus(orderId, status);
                                if (!result) {
                                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                                }
                            } catch (Exception e) {
                                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                            }
                        }
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }

    }
}
